package com.hbnu.ojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.hbnu.ojcodesandbox.model.ExecuteCodeRequest;
import com.hbnu.ojcodesandbox.model.ExecuteCodeResponse;
import com.hbnu.ojcodesandbox.model.ExecuteMessage;
import com.hbnu.ojcodesandbox.model.JudgeInfo;
import com.hbnu.ojcodesandbox.security.DenySecurityManager;
import com.hbnu.ojcodesandbox.unsafe.MemoryError;
import com.hbnu.ojcodesandbox.utils.ProcessUtils;
import jdk.internal.org.objectweb.asm.commons.StaticInitMerger;
import org.apache.http.impl.execchain.TunnelRefusedException;
import org.springframework.beans.factory.Aware;
import org.springframework.util.StopWatch;
import org.yaml.snakeyaml.util.ArrayUtils;
import sun.rmi.transport.StreamRemoteCall;

import javax.swing.text.StyledEditorKit;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;


/**
 * @Description: Java本地代码沙箱
 * @Author: Hu Bowen
 */
public class JavaDockerCodeSandbox implements CodeSandbox {

    // 全局代码名称
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    // 新线程的时间监控
    private static final long TIME_OUT = 5000L;  // 超时时间

    private static final Boolean FIRST_INIT = true; // 定义开关

    // 安全管理环境
    private static final String SECURITY_MANAGER_PATH = "C:\\code\\oj-code-sandbox\\src\\main" +
            "\\resources\\security";

    private static final String SECURITY_MANAGER_CLASS_NAME = "MySecurityManager";


    /**
     * 测试程序
     */
    public static void main(String[] args) {
        JavaDockerCodeSandbox javaNativeCodeSandbox = new JavaDockerCodeSandbox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "2 3"));
        // ! 指定程序的读取路径, 测试
        // 读取resource路径下的文件, 指定读取字符集utf-8
        String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java", StandardCharsets.UTF_8);
        // String code = ResourceUtil.readStr("testCode/unsafeCode/ReadError.java",
        //         StandardCharsets.UTF_8);

        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse); // 响应 null
    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {

        // 设置安全管理, 代码的对于系统权限的访问限制
        // System.setSecurityManager(new DenySecurityManager());

        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();


        // 1. 把用户的代码保存为文件
        String userDir = System.getProperty("user.dir");
        // File.separator文件分隔符常量
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局代码是否存在, 没有则新建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        // 把用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME; //
        // 通用的常量, 适合跨平台的程序
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        // 2. 编译代码, 得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s",
                userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);
        } catch (Exception e) {
            return getErrorResponse(e);
        }

        // 3. 创建容器, 把文件复制到容器内
        // 获取默认的Docker Client
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();

        // 拉取镜像
        String image = "openjdk:8-alpine";
        if (FIRST_INIT) {
            // 下载镜像
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
            // 拉取镜像结果回调
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                // 异步获取
                @Override
                public void onNext(PullResponseItem item) {
                    // 获取状态信息
                    System.out.println("下载镜像:" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd
                        .exec(pullImageResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("拉取镜像异常");
                throw new RuntimeException(e);
            }
            System.out.println("下载完成");
        }


        // 1. 创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig = new HostConfig();
        hostConfig.withMemory(100 * 1000 * 1000L);
        hostConfig.withCpuCount(1L);
        hostConfig.setBinds(new Bind(userCodeParentPath, new Volume("/app")));
        CreateContainerResponse createContainerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withAttachStdin(true)
                .withAttachStderr(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        System.out.println(createContainerResponse);
        String containerId = createContainerResponse.getId();

        // 2. 查看容器状态
        ListContainersCmd listContainersCmd = dockerClient.listContainersCmd();
        // 展示所有容器
        List<Container> containerList = listContainersCmd.withShowAll(true).exec();
        for (Container container : containerList) {
            // 遍历容器列表
            System.out.println(container);
        }
        // 启动容器
        dockerClient.startContainerCmd(containerId).exec();

        // 执行命令并获取结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray = inputArgs.split(" ");
            String[] cmdArray = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, inputArgsArray);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("创建执行命令：" + execCreateCmdResponse);

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};
            String execId = execCreateCmdResponse.getId();
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出结果错误" + errorMessage[0]);
                        super.onNext(frame);
                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果" + message[0]);
                    }
                    super.onNext(frame);
                }
            };
            try {
                stopWatch.start();  // 开启计时器
                dockerClient.execStartCmd(execId)
                        .exec(execStartResultCallback)
                        .awaitCompletion();
                stopWatch.stop(); // 关闭计时器
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            // 设置信息和错误信息, 添加执行信息
            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessage.setTime(time);
            executeMessage.setMemory(maxMemory);
            executeMessageList.add(executeMessage);
        }


        final long[] maxMemory = {0L}; // 最大内存值

        // 获取占用的内存
        StatsCmd statsCmd = dockerClient.statsCmd(containerId);
        // 统计结果回调
        ResultCallback<Statistics> statisticsResultCallback =
                statsCmd.exec(new ResultCallback<Statistics>() {

                    @Override
                    public void onNext(Statistics statistics) {
                        // 获取内存的状态
                        System.out.println("内存占用:" + statistics.getMemoryStats().getUsage());
                        maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                    }

                    @Override
                    public void onStart(Closeable closeable) {

                    }

                    @Override
                    public void onError(Throwable throwable) {

                    }

                    @Override
                    public void onComplete() {

                    }

                    @Override
                    public void close() throws IOException {

                    }
                });
        try {
            statsCmd.exec(statisticsResultCallback).close();
        } catch (IOException e) {
            e.printStackTrace();


        }


        // 4. 收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        return executeCodeResponse;
    }

    // 6. 错误处理, 提升程序健壮


    /**
     * 获取错误响应
     *
     * @param e
     * @return executeCodeResponse
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());

        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
        // 用户没有执行, 在编译中就存在的错误
    }
}
